// vr/pages/vr-form/vr-form.js
import areaData from '../../../utils/area.js'
import WxValidate from '../../../utils/wxValidate'

// 验证字段的规则
const rules = {
    title: {
        required: true,
    },
    province: {
        required: true,
    },
    detail: {
        required: true,
    }
}

// 验证字段的提示信息，若不传则调用默认的信息
const messages = {
    title: {
        required: '请填写信息标题',
    },
    province: {
        required: '请选择所在区域',
    },
    detail: {
        required: '请填写详细地址',
    }
}

const wxValidate = new WxValidate(rules, messages)


Page({

    /**
     * 页面的初始数据
     */
    data: {
        formData: {
            title: '',
            type: '1', // 1:图片2视频3vr
            house: '',
            price: '',
            province: '',
            city: '',
            district: '',
            detail: '',
            lng: '',
            lat: '',
            sort_num: '',
            gdbh: '', // 工地编号
            zxfg: '', // 装修风格
            zxjd: '', // 装修进度
            name: '',
            phone: '',
            product_name: '',
            construction_site_status: '',
            shooting_date:''
        },

        errorMessage: {
            title: '',
            type: 1, // 1:图片2视频3vr
            house: '',
            price: '',
            province: '',
            city: '',
            district: '',
            detail: '',
            lng: '',
            lat: '',
            sort_num: '',
            gdbh: '', // 工地编号
            zxfg: '', // 装修风格
            zxjd: '', //
            name: '',
            phone: '',
            product_name: '',
            construction_site_status: '',
            shooting_date:''
        },
        showAddress: false,
        areaList: areaData,
        showZxfg: false,
        zxfgDict: [], // 装修风格列表
        showZxjd: false,
        zxjdDict: [], // 装修进度列表
        showHouse: false,
        houseDict: [], // 户型
        gdStatus: false,
        gd_statusDict: [],

        product_codeDict: [],
        productStatus: false,
    },


    onConfirm(event) {
      this.setData({
        showCalendar: false,
        'formData.shooting_date': this.formatDate(event.detail),
      })
    },
    onClose() {
      this.setData({ showCalendar: false });
    },
    formatDate(date) {
      date = new Date(date);
      console.log(`${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`)
      return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
    },

    showShootingDateSheet(){
      this.setData({ showCalendar: true });
    },
    showAddressSheet() {
        this.setData({
            showAddress: true
        })
    },

    hideAddressSheet() {
        this.setData({
            showAddress: false
        })
    },

    confirmAddress(event) {
        const {
            values
        } = event.detail
        this.setData({
            'formData.province': values[0].name,
            'formData.city': values[1].name,
            'formData.district': values[2].name,
            showAddress: false
        })
    },
    showZxfgSheet() {
        this.setData({
            showZxfg: true
        })
    },
    hideZxfgSheet() {
        this.setData({
            showZxfg: false
        })
    },
    showProductStatusSheet() {
        this.setData({
            productStatus: true
        })
    },
    hideProductStatusSheet() {
        this.setData({
            productStatus: false
        })
    },
    showGdStatusSheet() {
        this.setData({
            gdStatus: true
        })
    },
    hideGdStatusSheet() {
        this.setData({
            gdStatus: false
        })
    },
    confirmZxfg(event) {
        console.log(event)
        const {
            value
        } = event.detail
        this.setData({
            'formData.zxfg': value,
            showZxfg: false
        })
    },

    showZxjdSheet() {
        this.setData({
            showZxjd: true
        })
    },
    hideZxjdSheet() {
        this.setData({
            showZxjd: false
        })
    },
    confirmZxjd(event) {
        const {
            value
        } = event.detail
        this.setData({
            'formData.zxjd': value,
            showZxjd: false
        })
    },

    showHouseSheet() {
        this.setData({
            showHouse: true
        })
    },
    hideHouseSheet() {
        this.setData({
            showHouse: false
        })
    },
    confirmHouse(event) {
        const {
            value
        } = event.detail
        this.setData({
            'formData.house': value,
            showHouse: false
        })
    },
    confirmProductStatus(event) {
        const {
            value
        } = event.detail
        this.setData({
            'formData.product_name': value,
            productStatus: false
        })
    },
    confirmGdStatus(event) {
        const {
            value
        } = event.detail
        this.setData({
            'formData.construction_site_status': value,
            gdStatus: false
        })
    },
    typeChange(event) {
        this.setData({
            'formData.type': event.detail,
        });
    },

    fieldChangeHandle(event) {
        const {
            name
        } = event.currentTarget.dataset
        const value = event.detail
        this.setData({
            [`formData.${name}`]: value
        })
    },

    blurHandle(event) {
        const {
            name
        } = event.currentTarget.dataset
        const value = this.data.formData[name]
        this.setData({
            [`errorMessage.${name}`]: wxValidate.validateField(name, value)
        })
    },
    submitHandle() {

        // 传入表单数据，调用验证方法
        if (!wxValidate.checkForm(this.data.formData)) {
            let errorMessage = {}

            wxValidate.errorList.forEach(item => {
                errorMessage[item.param] = item.msg
            })
            this.setData({
                errorMessage
            })
        } else {
            this.requestSave()
        }
    },

    requestSave() {
        let data = {
            ...this.data.formData
        }

        wx.ajax.post(!data.id ? 'addVrInfo.action' : 'updateVrInfo.action', data, true).then(res => {
            if (res.success) {
                wx.navigateBack({
                    delta: 1,
                })
            }
        })
    },

  async  getAllFindVrTypeList(){
        let arrDic=['zxfg','zxjd','house','product_code','gd_status']

        let list=await Promise.all(arrDic.map(async(type)=>{
           let {result}=await wx.ajax.get('findVrType.action', { type })
            return {
                type:`${type}Dict`,
                list:result.map(item => item.name)
            }
        }))
        
        list.map(item=>{
            this.setData({
                [item.type]:item.list
            })
        })




    },


    // 请求装修风格
    requestZxfg() {
        wx.ajax.get('findVrType.action', {
            type: 'zxfg'
        }).then(res => {
            if (res.success) {
                this.setData({
                    'zxfgDict': res.result.map(item => {
                        return item.name
                    })
                })
            }
        })
    },

    // 请求装修进度
    requestZxjd() {
        wx.ajax.get('findVrType.action', {
            type: 'zxjd'
        }).then(res => {
            if (res.success) {
                this.setData({
                    'zxjdDict': res.result.map(item => {
                        return item.name
                    })
                })
            }
        })
    },

    // 请求户型
    requestHouse() {
        wx.ajax.get('findVrType.action', {
            type: 'house'
        }).then(res => {
            if (res.success) {
                this.setData({
                    'houseDict': res.result.map(item => {
                        return item.name
                    })
                })
            }
        })
    },

    requestDetail() {
        wx.ajax.post(`findVrInfo.action?id=${this.vrId}`).then(res => {
            if (res.success) {
                this.setData({
                    formData: {
                        ...this.data.formData,
                        ...res.result
                    }
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {
            vrId
        } = options

        let title = "新增VR信息"

        if (vrId) {
            title = "编辑VR信息"
            this.vrId = vrId
            this.requestDetail()
        }

        wx.setNavigationBarTitle({
            title,
        })
        this.getAllFindVrTypeList()
        // this.requestZxjd()
        // this.requestZxfg()
        // this.requestHouse()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})